/*
 * GUI.java
 *
 * Created on 5 de Junho de 2007, 08:38
 */

package gui;

import java.io.File;
import java.util.ArrayList;

import javax.swing.JFileChooser;

import kMeans.core.Cluster;
import kMeans.core.KMeans;
import kMeans.core.PadraoTreinamento;
import kMeans.main.ManipulacaoArquivos;

/**
 *
 * @author  Jose
 */
public class GUI extends javax.swing.JFrame {
    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** Creates new form GUI */
    public GUI() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Cdigo Gerado ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextFieldTreino = new javax.swing.JTextField();
        jButtonArquivoTreino = new javax.swing.JButton();
        jButtonArquivoTeste = new javax.swing.JButton();
        jTextFieldTeste = new javax.swing.JTextField();
        jPanelConsole = new javax.swing.JPanel();
        jScrollPaneConsole = new javax.swing.JScrollPane();
        jTextAreaConsole = new javax.swing.JTextArea();
        jPanelBotoesRede = new javax.swing.JPanel();
        jButtonTreinar = new javax.swing.JButton();
        jButtonTestar = new javax.swing.JButton();
        jMenuBar = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuExit = new javax.swing.JMenuItem();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
        
        int numeroClusters = 0;
    	do {
    		numeroClusters = (int) (Math.random() * 10);
    	} while (numeroClusters == 0 || numeroClusters == 1);
    	
    	clustersK = new Cluster[numeroClusters];
        for (int i = 0; i < numeroClusters; i++) {
        	ArrayList<Double> clusterCenter = new ArrayList<Double>();
        	clusterCenter.add(Math.random());
        	clusterCenter.add(Math.random());
        	
        	clustersK[i] = new Cluster(i, 1.5, clusterCenter); //PoG!
    	}

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButtonArquivoTreino.setText("Arquivo Treino");
        jButtonArquivoTreino.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonArquivoTreinoActionPerformed(evt);
            }
        });

        jButtonArquivoTeste.setText("Arquivo Teste");
        jButtonArquivoTeste.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonArquivoTesteActionPerformed(evt);
            }
        });

        jPanelConsole.setBorder(javax.swing.BorderFactory.createTitledBorder("Console"));
        jTextAreaConsole.setColumns(20);
        jTextAreaConsole.setRows(5);
        jScrollPaneConsole.setViewportView(jTextAreaConsole);

        javax.swing.GroupLayout jPanelConsoleLayout = new javax.swing.GroupLayout(jPanelConsole);
        jPanelConsole.setLayout(jPanelConsoleLayout);
        jPanelConsoleLayout.setHorizontalGroup(
            jPanelConsoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPaneConsole, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
        );
        jPanelConsoleLayout.setVerticalGroup(
            jPanelConsoleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelConsoleLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPaneConsole, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jPanelBotoesRede.setBorder(javax.swing.BorderFactory.createTitledBorder("Rede"));
        jButtonTreinar.setText("Treinar");
        jButtonTreinar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonTreinarActionPerformed(evt);
            }
        });

        jButtonTestar.setText("Testar");
        jButtonTestar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonTestarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelBotoesRedeLayout = new javax.swing.GroupLayout(jPanelBotoesRede);
        jPanelBotoesRede.setLayout(jPanelBotoesRedeLayout);
        jPanelBotoesRedeLayout.setHorizontalGroup(
            jPanelBotoesRedeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelBotoesRedeLayout.createSequentialGroup()
                .addGap(104, 104, 104)
                .addComponent(jButtonTreinar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123, Short.MAX_VALUE)
                .addComponent(jButtonTestar)
                .addGap(114, 114, 114))
        );
        jPanelBotoesRedeLayout.setVerticalGroup(
            jPanelBotoesRedeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelBotoesRedeLayout.createSequentialGroup()
                .addGroup(jPanelBotoesRedeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonTestar)
                    .addComponent(jButtonTreinar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jMenuFile.setText("File");
        jMenuExit.setText("Exit");
        jMenuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuExitActionPerformed(evt);
            }
        });

        jMenuFile.add(jMenuExit);

        jMenuBar.add(jMenuFile);

        setJMenuBar(jMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanelConsole, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanelBotoesRede, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTextFieldTeste)
                            .addComponent(jTextFieldTreino, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButtonArquivoTeste, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButtonArquivoTreino, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldTreino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonArquivoTreino))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldTeste, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonArquivoTeste))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelBotoesRede, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanelConsole, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonTestarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestarActionPerformed
    	PadraoTreinamento [] aTest = new PadraoTreinamento[300];
    	if (this.getNmArquivoTreino().equals("")) {
			this.log("Nenhum arquivo selecionado para teste!");
		} else {
			aTest = manipArquivos.getTrainingData(this.getNmArquivoTreino());
		}
    	
    	ArrayList noveltyDetected = kMeans.test(aTest, clustersK);
    	
    	this.log("Parametros: Novelty Distance: "+clustersK[0].getNoveltyDistance()+"\t Threshold: "+Cluster.THRESHOLD+"\n");
	    this.log("            Clusters: "+clustersK.length +"\t      Execucoes para Treino: "+n+"\n");
	    this.log("Falsos Positivos: "+((Integer) noveltyDetected.get(0)).intValue() + "\tFalsos Negativos: "+((Integer) noveltyDetected.get(1)).intValue()+"\n");

    }//GEN-LAST:event_jButtonTestarActionPerformed

    private void jButtonTreinarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTreinarActionPerformed
    	PadraoTreinamento [] aTreinamento = new PadraoTreinamento[300];
    	if (this.getNmArquivoTreino().equals("")) {
			this.log("Nenhum arquivo selecionado para treino!");
		} else {
			aTreinamento = manipArquivos.getTrainingData(this.getNmArquivoTreino());
		}
        
	    boolean isCentroidMoving = true;
	    	        
	    while(isCentroidMoving && n < numMaxIterations) {
		    kMeans.train(aTreinamento, clustersK);
		    isCentroidMoving = kMeans.adjustCenter(clustersK, this);
		    n++;
	    }
        
    }//GEN-LAST:event_jButtonTreinarActionPerformed

    private void jButtonArquivoTesteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonArquivoTesteActionPerformed
        JFileChooser jFileChooser = new JFileChooser();
        int returnValue = jFileChooser.showOpenDialog(this);
        
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser.getSelectedFile();
            //This is where a real application would open the file.
            jTextFieldTeste.setText(file.getAbsolutePath());
        }
        
    }//GEN-LAST:event_jButtonArquivoTesteActionPerformed

    private void jButtonArquivoTreinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonArquivoTreinoActionPerformed
        JFileChooser jFileChooser = new JFileChooser();
        int returnValue = jFileChooser.showOpenDialog(this);
        
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser.getSelectedFile();
            //This is where a real application would open the file.
            jTextFieldTreino.setText(file.getAbsolutePath());
        }
    }//GEN-LAST:event_jButtonArquivoTreinoActionPerformed

    private void jMenuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jMenuExitActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUI().setVisible(true);
            }
        });
    }
    
    // Declarao de variveis - no modifique//GEN-BEGIN:variables
    private ManipulacaoArquivos manipArquivos = new ManipulacaoArquivos();
    private KMeans kMeans = new KMeans();
	private Cluster [] clustersK = null;
	private int numMaxIterations = 500;
	int n = 0;	
    
    private javax.swing.JButton jButtonArquivoTeste;
    private javax.swing.JButton jButtonArquivoTreino;
    private javax.swing.JButton jButtonTestar;
    private javax.swing.JButton jButtonTreinar;
    private javax.swing.JMenuBar jMenuBar;
    private javax.swing.JMenuItem jMenuExit;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JPanel jPanelBotoesRede;
    private javax.swing.JPanel jPanelConsole;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPaneConsole;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextAreaConsole;
    private javax.swing.JTextField jTextFieldTeste;
    private javax.swing.JTextField jTextFieldTreino;
    // Fim da declarao de variveis//GEN-END:variables
    
    public String getNmArquivoTreino() {
    	return jTextFieldTreino.getText();
    }
    
    public String getNmArquivoTeste() {
    	return jTextFieldTeste.getText();
    }
    
    public void log(String pLog) {
    	jTextAreaConsole.append(pLog);
    }
    
}
